/**
 * Created by wenguangjia on 2017/4/21.
 */

(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('svcSqlController', svcSqlController)
    svcSqlController.$inject = ['$scope', 'searchService'];
    function svcSqlController($scope, searchService) {
        $scope.partition='所有';
        $scope.param={kind:"",svc:null,type:"SQL",time:"500",startTime:getToday00Clock(),endTime:getToday11Clock(),partition:null,area:null};

        var array=new Array();//数据源
        var isLoadMore=true;//如果为false则不自动加载
        var requestData="";//requeste参数

        $scope.query=function(){
            requestData=generate();
            $scope.sqlGridOptions.dataSource.read();
        };

        //generate elasticsearch query template
        function generate(){
            array.length=0;
            var data={
                "query":{
                    "bool":{
                        "must": [],
                        "must_not":[],
                        "filter": [
                            { "match": { "category": "SVCSQL" } }
                        ]
                    }
                },
                "sort":{
                    "@timestamp":{
                        "order":"desc"
                    }
                },
                "size": 30,
                "from": 0
            };
            var data2={
                "query":{
                    "bool":{
                        "must": [],
                        "must_not":[],
                        "filter": [
                            { "match": { "category": "SVCSQL" } }
                        ]
                    }
                },
                "sort":{
                    "exec_time":{
                        "order":"desc"
                    }
                }
            };

            var obj=data['query']['bool'];
            switch ($scope.param.time){
                case '10':
                    data=data2;
                    break;
                case '500':
                    var arrayObj={ "range": { "exec_time":  {"gt" : 500} } };
                    obj.must.push(arrayObj);
                    break;
                case '1000':
                    var arrayObj={ "range": { "exec_time":  {"gt" : 1000} } };
                    obj.must.push(arrayObj);
                    break;
                case '5000':
                    var arrayObj={ "range": { "exec_time":  {"gt" : 5000} } };
                    obj.must.push(arrayObj);
                    break;
                case '10000':
                    var arrayObj={ "range": { "exec_time":  {"gt" : 10000} } };
                    obj.must.push(arrayObj);
                    break;
                case '30000':
                    var arrayObj={ "range": { "exec_time":  {"gt" : 30000} } };
                    obj.must.push(arrayObj);
                    break;
            }


            if($scope.param.partition!=undefined && $scope.param.partition!=null && $scope.param.partition!=""){
                var arrayObj={"term":{"partition":$scope.param.partition}};
                data['query']['bool'].filter.push(arrayObj);
            }
            if($scope.param.svc!=undefined && $scope.param.svc!=null && $scope.param.svc!=""){
                var arrayObj={"term":{"svc":$scope.param.svc}};
                data['query']['bool'].filter.push(arrayObj);
            }


            if($scope.param.type=="SVC"){
                var arrayObj={"match_phrase":{"logmsg":". service end"}};
                data['query']['bool'].must.push(arrayObj);
                if($scope.param.kind!=null && $scope.param.kind !=""){
                    if($scope.param.kind!='frame'){
                        arrayObj={"term":{"func":$scope.param.kind}};
                        data['query']['bool'].filter.push(arrayObj);
                        arrayObj={"wildcard":{"svc":"ep*"}};
                        data['query']['bool'].must_not.push(arrayObj);
                    }else{
                        arrayObj={"wildcard":{"svc":"ep*"}};
                        data['query']['bool'].filter.push(arrayObj);
                    }
                }
            }else if($scope.param.type=="SQL"){
                var arrayObj={"term":{"func":"SQL"}};
                data['query']['bool'].filter.push(arrayObj);
                //大类特征
                if($scope.param.kind!=null && $scope.param.kind !=""){
                    if($scope.param.kind=='frame'){
                        arrayObj={"wildcard":{"svc":"ep*"}};
                        data['query']['bool'].filter.push(arrayObj);
                    }else if($scope.param.kind=='BAT'){
                        arrayObj={"term":{"uid":"batch"}};
                        data['query']['bool'].filter.push(arrayObj);
                    }else if($scope.param.kind=='TEL'){
                        arrayObj={"term":{"formname.raw":"0"}};
                        data['query']['bool'].filter.push(arrayObj);
                    }else if($scope.param.kind=='SVC'){
                        arrayObj={"wildcard":{"svc":"ep*"}};
                        data['query']['bool'].must_not.push(arrayObj);
                        arrayObj={"term":{"uid":"batch"}};
                        data['query']['bool'].must_not.push(arrayObj);
                        arrayObj={"term":{"formname.raw":"0"}};
                        data['query']['bool'].must_not.push(arrayObj);
                    }
                }
            }
            if($scope.param.startTime!=null&&$scope.param.endTime==null){
                if($scope.param.startSecond!=0){
                    $scope.param.startTime.setSeconds($scope.param.startSecond);
                }else{
                    $scope.param.startTime.setSeconds(0);
                }
                var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime} } };
                data['query']['bool'].filter.push(arrayObj);
            }else if($scope.param.startTime==null&&$scope.param.endTime!=null){
                var arrayObj={ "range": { "@timestamp":  {"lt" : $scope.param.endTime} } };
                data['query']['bool'].filter.push(arrayObj);
            }else if($scope.param.startTime!=null&&$scope.param.endTime!=null){
                var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                data['query']['bool'].filter.push(arrayObj);
            }
            return data;
        }

        //文档高度
        function getDocumentTop() {
            var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
            if (document.body) {
                bodyScrollTop = document.body.scrollTop;
            }
            if (document.documentElement) {
                documentScrollTop = document.documentElement.scrollTop;
            }
            scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            return scrollTop;
        }
        //可视窗口高度
        function getWindowHeight() {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }
        //滚动条滚动高度
        function getScrollHeight() {
            var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
            if (document.body) {
                bodyScrollHeight = document.body.scrollHeight;
            }
            if (document.documentElement) {
                documentScrollHeight = document.documentElement.scrollHeight;
            }
            scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            return scrollHeight;
        }
        window.onscroll = function () {
            //监听事件内容
            if((getDocumentTop() + getWindowHeight() == getScrollHeight())&&isLoadMore){
                //当滚动条到底时,这里是触发内容
                //异步请求数据,局部刷新dom
                //requestData.from+=sourceCount;
                requestData.from+=30;
                $scope.sqlGridOptions.dataSource.read();
            }
        }

        /**
         * grid
         * @type {*[]}
         */
        var columns = [
            {field: "sourceId", hidden:true},
            {field: "partition", title: "分区", width: "60px"},
            {field: "timestamp", title: "生成时间",format:"{0: yyyy-MM-dd HH:mm:ss:fff}", width: "100px"},
            {field: "pid", title:"进程号",hidden:true},
            {field: "file_name", title:"文件名",hidden:true},
            {field: "priority", title:"优先级",hidden:true},
            {field: "source", title:"源目标",hidden:true},
            {field: "username", title:"用户名",hidden:true},
            {field: "ip", title:"IP",hidden:true},
            {field: "formname", title: "画面名", width: "40px"},
            {field: "msg", title: "消息", width: "180px"},
            {field: "exec_time", title: "耗时(ms)", width: "60px"},
            {field: "svc", title: "服务名", width: "80px"
                // template:function (dataItem) {
                //     var result='<a ui-sref="svcconsole" target="_blank" ng-click="setObj(dataItem)">{{dataItem.svc}}</a>';
                //     return result;
                // }
            },
        ];
        $scope.setObj=function(dataItem){
            var data={logmsg:dataItem.logmsg,svc:dataItem.svc,file_name:"",partition:dataItem.partition,'@timestamp':"",flag:dataItem.flag};
                // data['@timestamp']=new Date(dataItem.timestamp.getTime()-dataItem.key1);
                var fileName=dataItem.file_name.substring(6,dataItem.file_name.length);
                var newFileName=dataItem.svc+fileName;
                data.fileName=newFileName;
                // if($scope.param.type=='SVC'){
                //     data.logmsg='1. service begin';
                // }
                localStorage.setItem("svcConsoleObj",JSON.stringify(data));
        };
        $scope.sqlGridOptions={
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: columns,
            columnMenu:true,
        };
        $scope.sqlModel = kendo.data.Model.define({
            id: "sourceId",
            fields: {
                timestamp: {validation: {required: true}, type: 'date'},
            }
        });
        $scope.sqlGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    console.log(JSON.stringify(requestData));
                    searchService.query(requestData,$scope.param.area,'svcsql').then(function(resp){
                        console.log(resp);
                        var data=resp.data.hits.hits;
                        data.length==30?isLoadMore=true:isLoadMore=false;
                        //var array=new Array();
                        angular.forEach(data,function(item){
                            item._source.sourceId=item._id;
                            item._source.username=item._source.uid;
                            item._source.timestamp=item._source['@timestamp'];
                            item._source.msg=item._source.logmsg.substring(0,60);
                            array.push(item._source);
                        });
                        e.success(array);
                    },function(error){
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if (requestData=="") {
                    e.preventDefault();
                }
            },
            schema: {
                model: $scope.sqlModel
            }
        });

        /**
         * 分区配置
         * @type {string}
         */
        $scope.partition = '全部';
        var partitionSrc="";
        searchService.getPartition({}).then(
            function(resp){
                partitionSrc=resp.data;
                $scope.partitionSource=toTree(resp.data);
            },function(err){}
        );
        $scope.selectShow=function(item){
            if(item==0){
                $scope.param.area=null;
                $scope.param.partition=null;
                $scope.partition="全部";
            }
            angular.forEach(partitionSrc,function(k){
                if(item.ename==k.ename){
                    $scope.param.area=k.code;
                    $scope.param.partition=k.ename;
                    $scope.partition=item.fname+"-"+item.cname;
                }
            });
            $scope.win.close();
        };
    }

})();
